import { useParams } from 'react-router-dom';
import { Card, Col, message, Row, Tag, Button, QRCode, Modal } from 'antd';
import { cancelMakeAPI, createNativeAPI, fetchOrderInfoAPI, queryPayStatusAPI } from '@/api/memberAPI/orderDetailAPI';
import { useEffect, useRef, useState } from 'react';
import { OrderItem } from '@/type/orderType';
import qrCode from 'qrcode';
import './OrderDetail.scss';

export const OrderDetail = () => {
  const { orderId } = useParams();
  const [orderInfo, setOrderInfo] = useState({} as OrderItem);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [codeUrl, setCodeUrl] = useState<string>('');
  const [payStatus, setPayStatus] = useState<boolean>();
  const timeId = useRef<NodeJS.Timeout>();

  const handleCancel = () => {
    setIsModalOpen(false);
    clearInterval(timeId.current);
    message.warning('取消支付');
  };

  /**
   * @description 查询订单详情的回调函数
   * */
  const fetchOrderInfo = async () => {
    try {
      const { data } = await fetchOrderInfoAPI(orderId as string);
      setOrderInfo(data);
    } catch (error: any) {
      message.error(error.message);
    }
  };

  /**
   * @description 点击取消预约按钮的回调函数
   * */
  const cancelMake = async () => {
    try {
      const { data } = await cancelMakeAPI(orderId as string);
      await fetchOrderInfo();
      message.success('取消预约成功');
    } catch (error: any) {
      message.error(error.message);
    }
  };

  /**
   * @description 点击确认支付按钮的回调函数
   * */
  const submitOrder = async () => {
    try {
      setIsModalOpen(true);
      const { data } = await createNativeAPI(orderId as string);
      setCodeUrl(data.codeUrl);
      timeId.current = setInterval(async () => {
        const response = await queryPayStatusAPI(orderId as string);
        setPayStatus(response.data);
        if (!response.data) {

        } else {
          await fetchOrderInfo();
          setIsModalOpen(false);
          clearInterval(timeId.current);
          message.warning('支付成功');
        }
      }, 1000);
    } catch (error: any) {
      message.error(error.message);
    }
  };

  const renderButton = () => {
    if (orderInfo.orderStatus === 0) return <><Button size="large" type="primary" danger onClick={cancelMake}>取消预约</Button><Button size="large" type="primary" onClick={submitOrder}>确认支付</Button></>;
    if (orderInfo.orderStatus === -1) return null;
    if (orderInfo.orderStatus === 1) return <Button size="large" type="primary" danger onClick={cancelMake}>取消预约</Button>;
  };

  useEffect(() => {
    fetchOrderInfo();
  }, []);

  return (
    <div className="order-detail">
      <div className="header">
        <h2>挂号详情</h2>
      </div>
      <Card className="order-info">
        <div className="left">
          <i className="iconfont icon-chenggong"></i>
          <span>{orderInfo?.param?.orderStatusString}</span>
        </div>
        <div className="right">
          <QRCode size={80} errorLevel="H" value="https://ant.design/" icon="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" />
          <span>
             微信关注“尚医通预约挂号” 快速挂号，轻松就医
          </span>
        </div>
      </Card>
      <Card>
        <div className="boking-info">
          <div className="header">
            <i className="iconfont icon-guahao"></i>
            <span>挂号信息</span>
          </div>
          <Row gutter={16}>
            <Col className="gutter-row" span={8}>
              <div>就诊人姓名：{orderInfo?.patientName}</div>
            </Col>
            <Col className="gutter-row" span={8}>
              <div>就诊日期：{orderInfo?.reserveDate}</div>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col className="gutter-row" span={8}>
              <div>就诊医院：{orderInfo?.hosname}</div>
            </Col>
            <Col className="gutter-row" span={8}>
              <div>就诊科室：{orderInfo.depname}</div>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col className="gutter-row" span={8}>
              <div>医生职务：{orderInfo?.title}</div>
            </Col>
            <Col className="gutter-row" span={8}>
              <div>挂号时间：{orderInfo?.createTime}</div>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col className="gutter-row" span={8}>
              <div>医事服务费：<Tag color="#f50">￥{orderInfo?.amount}</Tag></div>
            </Col>
            <Col className="gutter-row" span={8}>
              <div>挂号单号：{orderInfo?.outTradeNo}</div>
            </Col>
          </Row>
        </div>
      </Card>
      <div className="waring">
        <Card>
          <div className="header">
            <i className="iconfont icon-zhuyi"></i>
            <span>注意事项</span>
          </div>
          <ol>
            <li>1:请确认就诊人信息是否准确，若填写错误将无法取号就诊，损失由本人承担；</li>
            <li>2:[取号]就诊当天需在{orderInfo.fetchTime}前在医院取号，未取号视为爽约，该号不退不换；</li>
            <li>3:[退号]在{orderInfo.quitTime}前可在线退号 ，逾期将不可办理退号退费；</li>
            <li>4:北京114预约挂号支持自费患者使用身份证预约，同时支持北京市医保患者使用北京社保卡在平台预约挂号。请于就诊当日，携带预约挂号所使用的有效身份证件到院取号；</li>
            <li>5:请注意北京市医保患者在住院期间不能使用社保卡在门诊取号。</li>
          </ol>
        </Card>
      </div>
      <div className="btn-box">
        {
          renderButton()
        }
      </div>
      <Modal className="code-modal" width={400} title="微信扫码支付" open={isModalOpen} onCancel={handleCancel}>
        <QRCode value={codeUrl || '-'}></QRCode>
      </Modal>
    </div>
  );
};


export default OrderDetail;
